/*
	后台-系统设置控制器
*/
'use strict';
var moment		= require('moment');
var AV 				= require('leanengine');
var mdCommon	= require('../modules/common');

var avSysConfig 	= AV.Object.extend("SysConfig");

/**
 * 列表页面
 * 2016.04.22  by 胡斌
 */
exports.tagPage = function(req, res) {
	//console.dir(req.AV.user);
	var name	= req.query.name;

	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.equalTo("name",name);
	querySysConfig.first().then(function(result){
		if(typeof(result)=="undefined"){
			var newSysConfig=new avSysConfig();
			newSysConfig.set("name",name);
			newSysConfig.set("type","tag");
			newSysConfig.set("value",new Array(0));
			return newSysConfig.save();
		}else{
			return AV.Promise.as(result);
		}
	}).then(function(result) {
		var val=result.get("value");
		res.render('admin-tag',{
			user:req.AV.user,
			results:val.split(","),
			moment:moment,
			name:name
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章管理-保存
 * 2015.05.24  by 胡斌
 */
exports.doSaveTag = function(req, res) {
	//console.log("doSave");
	var tagArr	= [];
	var name		= req.body.name;
	//console.log(req.query.tagArr);
	if(req.body.tagArr){
		tagArr=req.body.tagArr.split("||");
	}
	tagArr = tagArr.sort();
	//console.dir(tagArr);

	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.equalTo("name",name);
	querySysConfig.first().then(function(result){
		if(typeof(result)=="undefined"){
			var newSysConfig=new avSysConfig();
			newSysConfig.set("name",name);
			newSysConfig.set("type","tag");
			newSysConfig.set("value",tagArr.join(","));
			return newSysConfig.save();
		}else{
			newSysConfig=result;
			newSysConfig.set("value",tagArr.join(","));
			return newSysConfig.save();
		}
	}).then(function(result) {
		//console.dir(result);
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/config/tags?name='+name);
		}
	},function(error){
		console.dir(error);
		mdCommon.sentErr(res,req,error);
	});
}
